# -*- coding: utf-8 -*-
__author__ = 'Liantian'


from django import template
from django.utils.encoding import force_unicode

register = template.Library()



def in_group(user, groups):
    """Returns a boolean if the user is in the given group, or comma-separated
    list of groups.

    Usage::

        {% if user|in_group:"Friends" %}
        ...
        {% endif %}

    or::

        {% if user|in_group:"Friends,Enemies" %}
        ...
        {% endif %}

    """
    group_list = force_unicode(groups).split(',')
    return bool(user.groups.filter(name__in=group_list).values('name'))

register.filter('in_group', in_group)


def key(d, key_name):
    """
    Usage::
Filter's description is in summary. Example usage:
{{ dict|key:key_name }}
Filter:


    """

    return d[key_name]
key = register.filter('key', key)

def is_app_user(user, app_user):
    """Usage::

        {% if user|is_app_user:"WikiUser" %}
        ...
        {% endif %}


    """
    try:
        q = getattr(user,app_user)
        return True
    except:
        return False

register.filter('is_app_user', is_app_user)
